public member function
<memory>

std::shared_ptr::operator bool

explicit operator bool() const noexcept;
檢查是否非空
返回儲存的指標是否為 null 指標。

儲存的指標指向 shared_ptr 物件 解引用 的物件,這通常與其擁有的指標(銷燬時被刪除的指標)相同。如果 shared_ptr 物件是別名(例如,別名構造 的物件及其副本),則它們可能不同。

該函式返回的結果與get()!=0.

相同。請注意,一個 null shared_ptr(即此函式返回false的指標)不一定是一個空的 shared_ptr別名可能擁有某個指標但指向 null,或者擁有者組甚至可能擁有 null 指標(參見 建構函式 4 和 5)。

引數



返回值

false如果 shared_ptr 是 null 指標,則返回。
true否則。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// example of shared_ptr::operator bool
#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int(34));

  if (foo) std::cout << "foo points to " << *foo << '\n';
  else std::cout << "foo is null\n";

  if (bar) std::cout << "bar points to " << *bar << '\n';
  else std::cout << "bar is null\n";

  return 0;
}

輸出
foo is null
bar points to 34


另見